package com.macro.ai.other.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;

/**
 * @ClassName AudioModelController
 * @Description TODO
 * @Author wanghong
 * @Date 2025/6/21 15:01
 * @Version 1.0
 **/
@RestController
public class AudioModelController {

    @Autowired
    private DashScopeSpeechSynthesisModel speechSynthesisModel;

    private static final String TEXT = "床前明月光，疑是地上霜。";
    private static final String path = "/Users/wanghong/IdeaProjects/SpringAIProject/springai_other/src/main/resources/tts";

    @GetMapping("/tts")
    public void tts(){
        //创建SpeechSynthesisOptions
        DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()
                .withSpeed(1.0)
                .withPitch(0.9)
                .withVolume(60)
                .build();

        SpeechSynthesisResponse response = speechSynthesisModel.call(
                new SpeechSynthesisPrompt(TEXT, options)
        );

        File file = new File(path+"/output.mp3");

        try(FileOutputStream fos = new FileOutputStream(file)){
            ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
            fos.write(byteBuffer.array());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
